package com.net.tomcat5;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Administrator
 *
 * @author jiangbang
 * @date 2016/8/24
 */
public class Request {
    //请求方式
    private String method;
    //请求资源
    private String url;
    //请求参数
    private Map<String,Object> parameterMapValues;
    //内部
    public static final  String CRLF="\r\n";
    private InputStream is;
    private String requsetInfo;

    public Request(){
        method = "";
        url = "";
        parameterMapValues = new HashMap<String,Object>();
        requsetInfo = "";
    }

    public Request(InputStream is){
       this();
        this.is=is;

        try {
            byte[] data = new byte[20480];
            int len = is.read(data);
            requsetInfo = new String(data,0,len);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //分析头信息
        parseRequestInfo();
    }

    /**
     * 分析请求信息
     */
    private void parseRequestInfo(){
        if(null==requsetInfo || (requsetInfo=requsetInfo.trim()).equals("")){
            return;
        }
        String paramString ="";//接受请求参数
        //1。获取请求方式
        String firstLine = requsetInfo.substring(0,requsetInfo.indexOf(CRLF));
        int idx = requsetInfo.indexOf("/");//位置
        this.method = firstLine.substring(0,idx).trim();
        String urlStr = firstLine.substring(idx,firstLine.indexOf("HTTP/")).trim();
        if(this.method.equals("POST")){
             this.url=urlStr;
        }else if(this.method.equals("GET")){
            if(urlStr.contains("?")){//是否存在参数
                String[] urlArray = urlStr.split("\\?");
                this.url = urlArray[0];
                paramString = urlArray[1];//接受请求参数
            }else{
                this.url=urlStr;
            }
        }
        //不存在请求参数
        if(paramString==""){
            return;
        }
        //2、将请求参数封装到Map中
        parseParams(paramString);
    }

    private void parseParams(String paramString){
        //分割，将字符串转成数组
        StringTokenizer token = new StringTokenizer(paramString,"&");
        while(token.hasMoreElements()){
            String keyValue = token.nextToken();
            String[] keyvalues = keyValue.split("=");
             if(keyvalues.length==1){
                 keyvalues = Arrays.copyOf(keyvalues,2);
                 keyvalues[1] = null;
             }
            String key = keyvalues[0].trim();
            String value = keyvalues[1].trim();
            //转换为Map
            if(!parameterMapValues.containsKey(key)){
                parameterMapValues.put(key,value);
            }
        }
    }


    public Object getParameter(String param){
        return parameterMapValues.get(param);
    }

    public String getUrl(){
        return url;
    }
}
